package io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import javax.swing.JFileChooser;

/**
 * Class to export data from text area to a file
 * @author Balazs Pete
 *
 */
public class Out extends Thread{

	File file = null;
	
	/**
	 * Create and configure saving conditions
	 * @param path path to file (excl file name)
	 * @param fileName file name (excl extension and dot)
	 * @param extension file extension (excl the dot in front)
	 * @author Balazs Pete
	 */
	public Out(){
		JFileChooser ch = new JFileChooser();
		if(ch.showDialog(null, "Save") == JFileChooser.APPROVE_OPTION) {
			file = ch.getSelectedFile();
		}
		try {
			file = new File(file.getAbsolutePath()+".fole");
			file.createNewFile();
		} catch (IOException e1) {
			new errors.NoSuchFile();
		}
	}
	
	/**
	 * Save current text area to file
	 * @author Balazs Pete
	 */
	public void run(){
		try {
		    Writer out = new BufferedWriter(new OutputStreamWriter(
		        new FileOutputStream(file), "UTF-8"));
		    out.write(main.MainWindow.getText());
		    out.close();
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
			new errors.NoSuchFile();
		}
		
		try {
			//to dispose of the thread
			this.finalize();
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
	
}
